package cn.melonlib.security.encryption.comp.enc.aes;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.melonlib.security.encryption.comp.enc.SecurityRegister;
import cn.melonlib.security.encryption.model.EncPackage;
import lombok.Getter;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Repository
@Getter
@Lazy(false)
@ConditionalOnProperty(value = "system.security.enc.type",havingValue = "AES",matchIfMissing = true)
public class AesSecurityRegister  extends ApplicationObjectSupport implements SecurityRegister {

    private EncPackage storeKey;

    private EncPackage transmissionKey;
    private EncPackage oldTransmissionKey;

    @Value("${system.security.register:false}")
    private String registerVal;

    private boolean register = false;

    @Value("${system.security.key:MelonLibKey}")
    private String key;

    @Value("${system.security.key:MelonLibSecret}")
    private String secret;

    @Value("${system.security.name:aap}")
    private String securityName;

    @Resource
    private Environment env;

    @PostConstruct
    public void init() throws Exception {
        logger.info("初始化加密信息...");
//        transmissionKey = EncPackage.createEncPackage(SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded());
        this.register=BooleanUtils.toBoolean(registerVal);
        if (this.register) {
            byte[] keyData = DigestUtil.md5(securityName + "@" + key + ":" + secret);
            storeKey = EncPackage.createEncPackage(keyData);
            transmissionKey=EncPackage.createEncPackage(keyData);
        }
    }

    //    @Scheduled(fixedDelay = 7200000)
    public void reflashKeys() throws Exception {
        oldTransmissionKey = transmissionKey;
//        transmissionKey = EncPackage.createEncPackage(SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded());
        byte[] keyData = DigestUtil.md5(securityName + "@" + key + ":" + secret);
        transmissionKey=EncPackage.createEncPackage(keyData);
    }
}
